/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package cn.thread;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>Project: javaseapp - T5
 * <p>Powered by webrx On 2021-08-27 08:39:56
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 16
 */
public class T5 {
    //private  int num = 20;
    //private volatile int num = 20;
    private AtomicInteger num = new AtomicInteger(20);

    void work() {
        String n = Thread.currentThread().getName();
        while (true) {
            try {
                //TimeUnit.SECONDS.sleep(3);
                if (num.get() > 0) {
                    num.decrementAndGet();//此元子类操作方法，永远只有一个线程，默认使用的是volatile可见性来完成的。
                } else {
                    break;
                }
                System.out.printf("%s:%d ", n, num.get());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        var t = new T5();

        new Thread(t::work, "T1").start();
        new Thread(t::work, "T2").start();
        new Thread(t::work, "T3").start();
        new Thread(t::work, "T4").start();
    }
}
